<template>
  <!-- 库存管理 -->
  <div class="goods">
    <div class="search">
      <h1>库存管理</h1>
      <div class="search-input">
        <el-input
        v-model="queryInfo.goods_name"
        placeholder="商品名称"
      ></el-input>
      <el-input
        v-model="queryInfo.supplier_name"
        placeholder="商品厂家"
      ></el-input>
      <el-select
        v-model="queryInfo.goods_type"
        filterable
        placeholder="选择商品类型"
        clearable
      >
        <el-option
          v-for="item in goodsType"
          :key="item.key"
          :label="item.value"
          :value="item.key"
        >
        </el-option>
      </el-select>
      <el-button type="primary" icon="el-icon-search" @click="getGoods"
        >搜索</el-button
      >
      <el-button type="primary" icon="el-icon-plus" @click="showAdd"
        >添加库存商品</el-button
      >
      </div>
      

      <el-dialog
        title="添加库存"
        :visible.sync="addNumDialog"
        center
        width="20%"
        class="add-num"
      >
       <div style="text-align: center;"> <el-input-number
          v-model="addNum.num"
          :min="1"
          :max="10000"
          label="描述文字"
        ></el-input-number></div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addNumDialog = false" 
            >取 消</el-button
          >
          <el-button type="primary" @click="addGoodsNum">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 添加商品弹窗 -->
      <el-dialog
        :title="type == 'create' ? '添加商品' : '编辑商品信息'"
        :visible.sync="addDialogFormVisible"
        center
      >
        <el-form :model="addform" :rules="rules" ref="addform">
          <el-form-item
            label="商品名称"
            :label-width="formLabelWidth"
            prop="name"
          >
            <el-input
              v-model="addform.name"
              autocomplete="off"
              :disabled="type == 'create' ? false : true"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="商品规格"
            :label-width="formLabelWidth"
            prop="argument"
          >
            <el-input
              v-model="addform.specification"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="商品图片" :label-width="formLabelWidth">
            <!-- <el-input
              v-model="addform.goodsPicture"
              autocomplete="off"
            ></el-input> -->
            <el-upload
              class="upload-demo"
              action="/api/goods/img"
              :on-success="handleAvatarSuccess"
              :file-list="fileList"
              list-type="picture"
              name="goods_img"
              :headers="{ TOKEN: token }"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-form-item>
          <el-form-item
            label="商品类型"
            :label-width="formLabelWidth"
            prop="goods_type_id"
          >
            <el-select
              v-model="addform.goods_type_id"
              filterable
              placeholder="选择商品类型"
            >
              <el-option
                v-for="item in goodsType"
                :key="item.key"
                :label="item.value"
                :value="item.key"
              >
              </el-option>
            </el-select>
            <el-popover placement="top" width="280" v-model="addTypeVisible">
              商品名称：<el-input
                v-model="goodType"
                placeholder=""
                style="margin: 10px"
              ></el-input>
              <div style="text-align: center; margin: 0">
                <el-button
                  size="mini"
                  type="text"
                  @click="addTypeVisible = false"
                  >取消</el-button
                >
                <el-button type="primary" size="mini" @click="addGoodsType"
                  >确定</el-button
                >
              </div>
              <el-button slot="reference" type="primary"
                >添加商品类型</el-button
              >
            </el-popover>
          </el-form-item>
          <el-form-item
            label="供应商"
            :label-width="formLabelWidth"
            prop="supplier_id"
          >
            <el-select
              v-model="addform.supplier_id"
              filterable
              placeholder="选择供应商"
            >
              <el-option
                v-for="item in supplierList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="商品成本"
            :label-width="formLabelWidth"
            prop="cost"
          >
            <el-input v-model="addform.cost" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item
            label="商品售价"
            :label-width="formLabelWidth"
            prop="price"
          >
            <el-input v-model="addform.price" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addDialogFormVisible = false"
            >取 消</el-button
          >
          <el-button type="primary" @click="addGoods('addform')"
            >确 定</el-button
          >
        </div>
      </el-dialog>
    </div>

    <!-- 展示商品 -->
    <div class="table">
      <el-table
        :data="tableData"
        style="width: 100%"
        height="450"
        :default-sort="{ prop: 'date', order: 'descending' }"
      >
        <el-table-column type="selection" width="45" align="center">
        </el-table-column>
        <el-table-column
          type="index"
          :index="1 + (queryInfo.page - 1) * queryInfo.size"
          label="编号"
          width="60"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="name"
          label="商品名称"
          width="120"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="specification"
          label="商品规格"
          
          align="center"
        >
        </el-table-column>

        <el-table-column prop="img_url" label="商品图片" width="120">
          <template slot-scope="scope">
            <img
              :src="origin + scope.row.img_url"
              alt=""
              style="width: 60px; height: 60px"
            />
          </template>
        </el-table-column>

        <el-table-column prop="goods_type_name" label="商品类型" align="center">
        </el-table-column>
        <el-table-column prop="supplier_name" label="商品厂家" align="center">
        </el-table-column>
        <el-table-column
          prop="inventory"
          label="商品数量"
          sortable
          align="center"
        >
        </el-table-column>
        <el-table-column prop="cost" label="商品成本" sortable align="center">
        </el-table-column>
        <el-table-column prop="price" label="商品售价" sortable align="center">
        </el-table-column>
        <el-table-column prop="profit" label="商品利润" sortable align="center">
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <!-- 删除 -->
            <i
              class="icon-shanchu iconfont"
              style="color: red; margin-right: 5px"
              @click="deleteGoods(scope.row.id)"
            ></i>
            <!-- 修改 -->
            <i
              class="icon-xiugai2 iconfont"
              style="color: #4064e1"
              @click="showUpdateDialog(scope.row)"
            ></i>
            <i
              class="el-icon-circle-plus-outline"
              @click="showAddNum(scope.row)"
              style="margin-left: 5px; color: #3fb883; font-size: 16px"
            ></i>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.page"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="queryInfo.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
// import { addGoods } from "../api/index";
import {
  getGoodsList,
  addGoods,
  addGoodsNumber,
  editGoodsNumber,
  delGoods,
  updateGoodsImg,
  getGoodsDetail,
  editGoodsInfo,
  getGoodsType,
  addGoodsType,
} from "../api/goods";
import { getSupplierList } from "@/api/supplier";
export default {
  data() {
    return {
      token: window.localStorage.getItem("token"),
      addTypeVisible: false,
      goodType: "",
      supplierList: [],
      origin: "http://127.0.0.1:8000/",
      tableData: [],
      goodsType: {},
      supplier: [],
      addform: {
        name: "",
        specification: "",
        img_url: "",
        goods_type_id: "",
        supplier_id: 27,
        cost: "",
        price: "",
      },
      rules: {
        name: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
        goods_type_id: [{ required: true, message: "请选择", trigger: "blur" }],
        cost: [{ required: true, message: "请输入", trigger: "blur" }],
        price: [{ required: true, message: "请输入", trigger: "blur" }],
        supplier_id: [{ required: true, message: "请选择", trigger: "blur" }],
      },
      updateDialogVisible: false,
      addDialogFormVisible: false,
      addNumDialog: false,
      formLabelWidth: "120px",
      updateFormRulues: [],
      //查询信息实体
      queryInfo: {
        page: 1, //当前页
        size: 10, //每页最大数
      },
      total: 0, //总记录数
      fileList: [],
      type: "create",
      addNum: {
        name: "",
        num: 0,
        id: "",
      },
    };
  },
  methods: {
    //获取所有商品
    async getGoods() {
      getGoodsList(this.queryInfo).then((res) => {
        this.tableData = res.data;
        this.total = res.total;
      });
    },
    //最大数
    handleSizeChange(newSize) {
      this.queryInfo.size = newSize;
      this.getGoods();
    },
    //pageNum的触发动作
    handleCurrentChange(newPage) {
      
      this.queryInfo.page = newPage;
      this.getGoods();
    },

    async deleteGoods(id) {
      const confirmResult = await this.$confirm(
        "此操作将会永久删除商品，是否继续？",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmResult != "confirm") {
        return this.$message.info("已取消删除");
      }

      delGoods(id).then(() => {
        this.$message.success("操作成功！");
        this.getGoods();
      });
    },

    showUpdateDialog(currentData) {
      this.addDialogFormVisible = true;
      this.type = "update";
      getGoodsDetail(currentData.id).then((res) => {
        this.addform = res;
      });
    },
    showAdd() {
      this.addDialogFormVisible = true;
      this.addform = {};
      this.type = "create";
    },
    showAddNum(currentData) {
      this.addNumDialog = true;
      this.addNum.id = currentData.id;
    },
    closeUpdateDialog() {
      this.updateDialogVisible = false;
      this.getGoods();
    },
    //增加
    async addGoods(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.addDialogFormVisible = false;
          if (this.type == "create") {
            addGoods({ ...this.addform }).then((res) => {
              this.$message.success("操作成功！");
              this.getGoods();
              this.addform = {};
              this.fileList = [];
            });
          } else {
            console.log("this.addform", this.addform);
            editGoodsInfo(this.addform.id, this.addform).then((res) => {
              this.$message.success("操作成功！");
              this.getGoods();
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });

      //this.addform.goodsPicture=sessionStorage.getItem("imgUrl");
    },
    addGoodsNum() {
      const params = {
        inventory: this.addNum.num,
      };
      addGoodsNumber(this.addNum.id, params).then((res) => {
        this.addNumDialog = false;
        this.getGoods();
        this.addNum.num = 0;
      });
    },
    //获取商品类型
    async getGoodsType() {
      getGoodsType().then((res) => {
        // this.goodsType = res;
        let items = [];
        for (var i in res) {
          items.push({
            key: Number(i),
            value: res[i],
          });
        }
        this.goodsType = items;
      });
    },

    handleAvatarSuccess(res, file) {
      this.addform.img_url = res.data.img_url;
    },

    addGoodsType() {
      addGoodsType({ name: this.goodType }).then(() => {
        this.addTypeVisible = false;
        this.getGoodsType();
        this.goodType = "";
      });
    },
  },
  created() {
    this.getGoods();
    this.getGoodsType();

    getSupplierList({ page: 1, size: 999 }).then((res) => {
      this.supplierList = res.data;
    });
  },
  mounted() {},
  computed: {},
};
</script>

<style lang="less" scoped>
.goods {
  margin: 0 10px;
}
h1 {
  font-size: 24px;
  font-weight: 400;
  padding-bottom: 10px;
  color: #565758;
}
.el-select {
  margin-right: 20px;
}
.search {
  .el-button--primary {
    background-color: #4064e1;
    border: 0 !important;
  }
}
.table {
  margin-top: 40px;
  overflow: auto;
}
.search{
  .search-input{
    .el-input {
  width: 150px;
  margin-right: 20px;
}
  }
  
}

.pagination {
  width: 400px;
  margin: 10px auto;
}
</style>
